package com.chainyoung.component_tmperson.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.airbnb.lottie.LottieAnimationView;
import com.chainyoung.common.base.BaseActivity;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.component_tmperson.R;
import com.chainyoung.component_tmperson.R2;
import com.chainyoung.component_tmperson.di.component.DaggerPersonActivityComponent;
import com.chainyoung.component_tmperson.di.module.PersonActivityModule;
import com.chainyoung.component_tmperson.ui.mvp.contract.AboutProtocolContact;
import com.chainyoung.component_tmperson.ui.mvp.presenter.ProtocolPresenter;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.chainyoung.common.constant.CommonStringConstants.URL;

public class ProtocolActivity extends BaseActivity<ProtocolPresenter> implements AboutProtocolContact.View {


    @BindView(R2.id.webView)
    WebView mWebView;
    @BindView(R2.id.LottieAnimationView)
    com.airbnb.lottie.LottieAnimationView mLottieAnimationView;

    private String url,js,title;

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerPersonActivityComponent.builder()
                .appComponent(appComponent)
                .personActivityModule(new PersonActivityModule(this))
                .build()
                .inject(this);
    }


    @Override
    protected void initUI() {
        initSetting();
        setCurrentTitle(R.string.about_protocol);
        url = getIntent().getStringExtra(URL);
        initSetting();
        js = "var script = document.createElement('meta');\" \"script.name = 'viewport';\" \"script.content=\\\"width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\\\";\" \"document.getElementsByTagName('head')[0].appendChild(script);\"";
    }

    @Override
    protected void initData() {
        mPresenter.getProtocol();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_web_view;
    }

    @Override
    public void showProtocol(String data) {
        setCurrentTitle(R.string.about_protocol);
        mWebView.getSettings().setDefaultFontSize(40);
        mWebView.loadDataWithBaseURL(null, data, "text/html", "UTF-8", null);
    }


    @SuppressLint("NewApi")
    private void initSetting() {
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        if (Build.VERSION.SDK_INT >= 19) {
            webSettings.setLoadsImagesAutomatically(true);//图片自动缩放 打开
        } else {
            webSettings.setLoadsImagesAutomatically(false);//图片自动缩放 关闭
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);//软件解码
        }
        mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);//硬件解码

        webSettings.setJavaScriptEnabled(true); // 设置支持javascript脚本
//        webSettings.setPluginState(WebSettings.PluginState.ON);
        webSettings.setSupportZoom(true);// 设置可以支持缩放
        webSettings.setBuiltInZoomControls(true);// 设置出现缩放工具 是否使用WebView内置的缩放组件，由浮动在窗口上的缩放控制和手势缩放控制组成，默认false

        webSettings.setDisplayZoomControls(false);//隐藏缩放工具
        webSettings.setUseWideViewPort(true);// 扩大比例的缩放
        //mWebView.getSettings().setDefaultFontSize(40);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//自适应屏幕
        webSettings.setLoadWithOverviewMode(true);

        webSettings.setSupportMultipleWindows(true);//支持多窗口

        webSettings.setAllowContentAccess(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setAllowFileAccess(true);

        webSettings.setDatabaseEnabled(true);//
        webSettings.setSavePassword(true);//保存密码
        webSettings.setDomStorageEnabled(true);//是否开启本地DOM存储  鉴于它的安全特性（任何人都能读取到它，尽管有相应的限制，将敏感数据存储在这里依然不是明智之举），Android 默认是关闭该功能的。
        mWebView.setSaveEnabled(true);
        mWebView.setKeepScreenOn(true);

        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });


        // 设置setWebChromeClient对象
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);

            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO Auto-generated method stub
                mLottieAnimationView.setProgress(newProgress);
                super.onProgressChanged(view, newProgress);
            }


        });
        //设置此方法可在WebView中打开链接，反之用浏览器打开
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (!mWebView.getSettings().getLoadsImagesAutomatically()) {
                    mWebView.getSettings().setLoadsImagesAutomatically(true);
                }
                mLottieAnimationView.setVisibility(View.GONE);
//                mWebView.evaluateJavascript(js, new ValueCallback<String>() {
//                    @Override
//                    public void onReceiveValue(String value) {
//                        //此处为 js 返回的结果
//                        Log.v("webview",value);
//                    }
//                });


            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                mLottieAnimationView.setVisibility(View.VISIBLE);

                super.onPageStarted(view, url, favicon);
//                if (url.equals(ServerConstant.BMGAME_DOWNLOAD)) {
//                    if (AppUtils.isInstallApp(mContext, PkgName.BM_GAME.pkgName)) {
//                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(ServerConstant.BM_URI));
//                        startActivity(intent);
//                    }
//                }
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if ((url.startsWith("http:") || url.startsWith("https:"))) {
                    view.loadUrl(url);
                    return false;
                }
//                if (url.equals(ServerConstant.BMGAME_DOWNLOAD)) {
//                    if (AppUtils.isInstallApp(mContext, PkgName.BM_GAME.pkgName)) {
//                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(ServerConstant.BM_URI));
//                        startActivity(intent);
//                    }
//                }
                return true;
            }
        });
        if (!TextUtils.isEmpty(url)) {
            mWebView.loadUrl(url);
        }

        mWebView.addJavascriptInterface(new JavaScriptinterface(this),
                "android");


    }


    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    class JavaScriptinterface {
        Context context;

        public JavaScriptinterface(Context c) {
            context = c;
        }

        /**
         * 与js交互时用到的方法，在js里直接调用的
         */
        @JavascriptInterface
        public void onFinish() {
            finish();
        }
    }


}
